package com.biqee.framework.interceptor;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.biqee.exception.AuthenticationFailedException;
import com.biqee.framework.context.RequestContext;
import com.biqee.model.db.BqUser;
import com.biqee.model.db.UserVersion;
import com.biqee.service.user.UserPermissionService;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.ActionProxy;
import com.opensymphony.xwork.interceptor.Interceptor;

/**
 * 用户权限检查拦截器
 * 
 * @author guotao.tangt
 *
 */
public class AuthenticationInterceptor implements Interceptor {
	private static final long serialVersionUID = -8790128705531961638L;

	public void init() {

	}

	public void destroy() {

	}

	public String intercept(ActionInvocation invocation) throws Exception {
		if(!checkPermission(invocation)) {
			throw new AuthenticationFailedException("no permission");
		}
		
		return invocation.invoke();
	}
	
	private boolean checkPermission(ActionInvocation invocation) {
		if(!isNeedCheck(invocation)) {
			return true;
		}

		BqUser bqUser = RequestContext.getUser();
		List<UserVersion> userVersions = RequestContext.getUserVersions();
		if(bqUser == null || userVersions == null) {
			return false;
		}
				
		ServletContext servletContext = ServletActionContext.getServletContext(); 
		WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);  
		UserPermissionService userPermissionService = (UserPermissionService)webApplicationContext.getBean("userPermissionService");
		String currentPermissionCode = getPermissionCode(invocation);
		return userPermissionService.checkPermission(userVersions, currentPermissionCode);
	}

	private String getPermissionCode(ActionInvocation invocation) {
		ActionProxy proxy = invocation.getProxy();
		String namespace = "";
		if (proxy.getNamespace() != null) {
			namespace = proxy.getNamespace().substring(1);
		}
		
		String actionName = proxy.getActionName();
		// String method = proxy.getMethod();

		return "ACTION_" + namespace + "_" + actionName;
	}
	
	/**
	 * modify this method if any white list needed
	 * @param invocation
	 * @return
	 */
	private boolean isNeedCheck(ActionInvocation actionInvocation) {
		ActionProxy proxy = actionInvocation.getProxy();
		String actionName = proxy.getActionName().toLowerCase();
		for(String ignoreAction : ignoreActionList) {
			if(ignoreAction.equals(actionName)) {
				return false;
			}
		}
		
		return true;
	}

	private static List<String> ignoreActionList = new ArrayList<String>();
	
	static {
		// TODO load from config files
		ignoreActionList.add("login");
	}
	
}
